package com.cxs.shopstore.service.impl;

import com.cxs.shopstore.service.FileUploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/*
 * @Author:cxs
 * @Date:2021/5/9  9:15
 * @Version 1.0
 * 图片上传业务类
 * */
@Slf4j
@Service
public class FileUploadServiceImpl implements FileUploadService {
    @Override
    public String imgupload(MultipartFile multipartFile, String path) {
        //文件原路径
        String originalFilename = multipartFile.getOriginalFilename();
        //重命名文件
        String fileName = UUID.randomUUID().toString().replaceAll("-","")
                + originalFilename.substring(originalFilename.lastIndexOf("."));
        File file = new File(path);
        //判断目录是否存在
        if(!file.exists()){
            file.mkdir();
            try {
                //保存文件，返回路径
                multipartFile.transferTo(new File(file,fileName));
                return path + fileName;
            } catch (IOException e) {
                log.error("",e);
                e.printStackTrace();
            }
        }else{
            try {
                //保存文件，返回路径
                multipartFile.transferTo(new File(file,fileName));
                return path + fileName;
            } catch (IOException e) {
                log.error("",e);
                e.printStackTrace();
            }
        }
        return "";
    }
}
